<template>
  <el-button
    :type="isFollowing ? 'info' : 'primary'"
    :loading="loading"
    @click="handleFollowClick"
  >
    {{ buttonText }}
  </el-button>
</template>

<script>
import { ref, onMounted } from 'vue'
import { followApi } from '@/api/follow'
import { ElMessage } from 'element-plus'

export default {
  name: 'FollowButton',
  props: {
    // 当前登录用户ID
    currentUserId: {
      type: Number,
      required: true
    },
    // 要关注的用户ID
    targetUserId: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    const loading = ref(false)
    const isFollowing = ref(false)
    const buttonText = ref('关注')

    // 检查关注状态
    const checkFollowStatus = async () => {
      try {
        const response = await followApi.checkFollowStatus(
          props.currentUserId,
          props.targetUserId
        )
        isFollowing.value = !!response.data
        buttonText.value = isFollowing.value ? '已关注' : '关注'
      } catch (error) {
        console.error('检查关注状态失败:', error)
      }
    }

    // 处理关注/取消关注点击
    const handleFollowClick = async () => {
      if (loading.value) return
      loading.value = true

      try {
        if (isFollowing.value) {
          await followApi.unfollowUser(props.currentUserId, props.targetUserId)
          ElMessage.success('取消关注成功')
          isFollowing.value = false
          buttonText.value = '关注'
        } else {
          await followApi.followUser(props.currentUserId, props.targetUserId)
          ElMessage.success('关注成功')
          isFollowing.value = true
          buttonText.value = '已关注'
        }
      } catch (error) {
        ElMessage.error('操作失败，请重试')
        console.error('关注操作失败:', error)
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      checkFollowStatus()
    })

    return {
      loading,
      isFollowing,
      buttonText,
      handleFollowClick
    }
  }
}
</script> 